/*
 * @Description: 图片检索
 * @Author: ZzT
 * @Date: 2023-03-02 17:48:03
 * @LastEditTime: 2023-03-03 20:16:35
 */
import { fetchRepoList } from '@/api/archivesType';

import { Button, message, UploadProps, Upload, Select, Spin } from 'antd';
import classNames from 'classnames/bind';
import styles from '../styles/seach.module.scss';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { RcFile, UploadChangeParam, UploadFile } from 'antd/lib/upload';
import { uploadPath } from '@/api/upload';
import { useNavigate } from 'react-router-dom';
import { submitImageSearch } from '@/api/search';

const cx = classNames.bind(styles);

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  // eslint-disable-next-line n/no-callback-literal
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: any) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const ImageSearchFrame = (props: any) => {
  const { conditions, fieldConditionList } = props;
  const [loading, setLoading] = useState(false);
  const [imgUrl, setImgUrl] = useState<string>();
  const [login, setLogin] = useState(false);
  /* 获取dbName */
  const [dbNameList, setDbNameList] = useState([]);
  const [dbName, setDbName] = useState('data');

  const navigate = useNavigate();

  /* 选取dbName */
  useEffect(() => {
    fetchRepoList({ atType: 1 }).then((res: any) => {
      const { data } = res;
      setDbNameList(data);
    });
  }, []);

  const changeDbName = (eve: any) => {
    setDbName(eve);
  };

  const handleChange: UploadProps['onChange'] = ({ file }: UploadChangeParam<UploadFile>) => {
    const { response } = file;
    if (file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (file.status === 'done') {
      // Get this url from response in real world.
      getBase64(file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImgUrl(response.data.url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  const submitSearch = () => {
    setLogin(true);
    const fondsConditionList = conditions;
    console.log(fondsConditionList);
    if (fondsConditionList.length === 0 || fondsConditionList[0].atConditionList.length === 0) {
      message.warning('请选择档案类型');
      return;
    }
    const commonParams = { dbName };
    const query = {
      pageNo: 1,
      pageSize: 3
    };

    const param = { fondsConditionList, commonParams, imgUrl };
    console.log('submit', { ...query, param });

    submitImageSearch({ ...query, param })
      .then((res: any) => {
        const { data } = res;
        navigate('../image-result', {
          state: { data, params: { ...query, param }, type: 4 }
          // state: { params: { ...query, param }, type: 4 }
        });
      })
      .finally(() => setLogin(true));
  };

  return (
    <>
      <div className={cx('imageFlow')}>
        <p>①上传相关媒体资源→②选择检索条件→③点击检索</p>
        <div>
          <Select
            className="select-before"
            style={{ width: 120 }}
            defaultValue="data"
            options={dbNameList}
            fieldNames={{ label: 'description', value: 'name' }}
            onChange={changeDbName}
          />
          <Button type="primary" onClick={() => submitSearch()}>
            检索
          </Button>
        </div>
      </div>
      <Spin size="large" spinning={login}>
        <div className={cx('image-upload')}>
          <Upload
            name="file"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action={uploadPath}
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imgUrl ? <img src={imgUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        </div>
      </Spin>
    </>
  );
};
export default ImageSearchFrame;
